package velox.jcr.spring;

import java.io.File;

import javax.jcr.Repository;

import org.apache.jackrabbit.core.TransientRepository;
import org.apache.jackrabbit.core.TransientRepository.RepositoryFactory;
import org.apache.jackrabbit.core.fs.local.FileUtil;
import org.springmodules.jcr.jackrabbit.RepositoryFactoryBean;

public class TransientRepositoryFactoryBean extends RepositoryFactoryBean {
	private RepositoryFactory repositoryFactory;
	private boolean cleanHomeDir;
	
	public boolean isCleanHomeDir() {
		return cleanHomeDir;
	}

	public void setCleanHomeDir(boolean cleanHomeDir) {
		this.cleanHomeDir = cleanHomeDir;
	}

	public RepositoryFactory getRepositoryFactory() {
		return repositoryFactory;
	}
	
	@Override
	protected void resolveConfigurationResource() throws Exception {
		if (cleanHomeDir) {
			File f = getHomeDir().getFile();
			if (f.exists()) {
				FileUtil.delete(f);
				f = getHomeDir().getFile();
				f.mkdirs();
			} else {
				f.mkdirs();
			}
		}

		super.resolveConfigurationResource();
	}

	@Override
	protected Repository createRepository() throws Exception {
		
		// use given factory
		if (repositoryFactory != null)
			return new TransientRepository(repositoryFactory);

		// fallback to discovered repository configuration
		return new TransientRepository(getRepositoryConfig());
	}

}